package com.tiny.controller;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.tiny.model.Dictionary;

public class DictionaryController extends Controller {

	public void index() {
		render("/frame/dictionary.html");
	}
	
	public void query(){
		StringBuilder sql = new StringBuilder(" from dictionary where 1=1 ");

		if (StrKit.notBlank(this.getPara("parent_id"))) {
			sql.append(String.format(" and parent_id = '%s' ",
					this.getPara("parent_id")));
		}
		if (StrKit.notBlank(this.getPara("parent_id"))) {
			sql.append(String.format(" and parent_id = '%s' ",
					this.getPara("parent_id")));
		}
		
		sql.append(" order by id desc ");
		
		Page<Dictionary> page = Dictionary.dao.paginate(this.getParaToInt("page"), this.getParaToInt("rows"),"select * ", sql.toString());
		
		renderJson(page.getList());
	}
	
	public void parentDict(){
		renderJson(Db.find(" select id,name from dictionary where parent_id=0 union all select 0,'  ' "));
	}
	
	public void dict(){
		renderJson(Db.find(" select id,name from dictionary where parent_id=? ",this.getPara("id")));
	}
	
	public void save(){
		Dictionary dic = getModel(Dictionary.class);
		
		if (StrKit.notBlank(this.getPara("parent_id"))) {
			dic.set("parent_id", this.getPara("parent_id"));
		}
		else{
			dic.set("parent_id", 0);
		}
		dic.set("name", this.getPara("name"));
		dic.set("value", this.getPara("value"));
		dic.set("order", this.getPara("order"));

		setAttr("success", dic.save());
		renderJson();
	}
	
	public void edit(){
		Dictionary dic = getModel(Dictionary.class);
		
		if (StrKit.notBlank(this.getPara("parent_id"))) {
			dic.set("parent_id", this.getPara("parent_id"));
		}
		else{
			dic.set("parent_id", 0);
		}
		dic.set("name", this.getPara("name"));
		dic.set("value", this.getPara("value"));
		dic.set("order", this.getPara("order"));
		dic.set("id", this.getPara("id"));
		
		setAttr("success", dic.update());
		renderJson();
	}
	
	public void remove(){
		setAttr("success", Db.update(" delete from dictionary where id=? or parent_id=? ",this.getPara("id"),this.getPara("id")));
		renderJson();
	}
	
	public void getDicts(){
		renderJson(Db.find(" select * from dictionary where parent_id=( select id from dictionary where name=?)",this.getPara("name")));
	}
}